package web.test.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import web.test.bean.Result;
import web.test.exception.BizException;

import javax.servlet.http.HttpServletRequest;

//@RestController
public class GlobalErrorController implements org.springframework.boot.web.servlet.error.ErrorController {

	@Override
	public String getErrorPath() {
		return "/error";
	}

	@RequestMapping("/error")
	public Result error(HttpServletRequest request) {
		Result result = new Result<>();
		Exception exception = (Exception) request.getAttribute("javax.servlet.error.exception");
		int httpCode = (int) request.getAttribute("javax.servlet.error.status_code");

		if (exception instanceof BizException) {
			// 如果是你手动抛出的鉴权失败的异常，获取errorCode和msg，进行提示，此时errorCode默认返回200，因为表示成功返回
			BizException bizException = (BizException) exception;
			result.setErrorCode(bizException.getCodeMsg().getValue());
			result.setMsg(bizException.getCodeMsg().getErrMsg());
		} else {
			// 有其他异常产生，那么返回spring原始的状态码，比如500， 400等
			result.setErrorCode(httpCode);
			result.setMsg(exception.getMessage());
		}

		System.out.println("error controller run");

		return result;
	}
}
